import * as actionTypes from './actionTypes';

export function fetchWeatherStarted() {
	return ({
		type: actionTypes.FETCH_STARTED
	});
}

export function fetchWeatherSuccess(result) {
	return ({
		type: actionTypes.FETCH_SUCCESS,
		result
	});
}

export function fetchWeatherFailure(error) {
	return ({
		type: actionTypes.FETCH_FAILURE,
		error
	});
}

export function fetchWeather(cityCode) {
	return ((dispatch, getState) => {
        let apiUrl = `data/cityinfo/${cityCode}.html`;
        if(__DEV__) {
            apiUrl = `/data/cityinfo/${cityCode}.html`;
        }
		dispatch(fetchWeatherStarted());
		fetch(apiUrl).then((response) => {
			if(response.status !== 200) {
				throw new Error('Fail to get response with status ' + response.status);
			}

			response.json().then((responseJson) => {
				dispatch(fetchWeatherSuccess(responseJson.weatherinfo));
			}).catch((error) => {
				throw new Error('Invalid json response ' + error);
			});
		}).catch((error) => {
			dispatch(fetchWeatherFailure(error));
		});
	});
}
			